<!--手动交易-合约-交易所、交易对-->
<template>
  <div class="vt-pair">

    <div v-if="api" class="row acenter" @click="apiClick">
      <LImage class="img-exchange" :src="Config.img('v2_'+api.exchangeName.toLowerCase()+'.png')"></LImage>
      <text class="font28 text1">{{api.apiName+'('+T('合约')+')'}}</text>
      <LImage class="img-arrow-down" :src="Config.img('trading_triangle_white.png')"></LImage>
    </div>
    
    <div v-if="pair" class="row acenter" @click="parClick">
      <text class="font28 text1">{{pair.counterCoin+T('永续')+'/'+pair.baseCoin}}</text>
      <LImage class="img-arrow-down" :src="Config.img('trading_triangle_white.png')"></LImage>
    </div>
  </div>
</template>


<script>
import jconfig from "@/_js/config"
import jhttps from "@/_js/https"
import jmodal from "@/_js/modal"
import japi from "@/_js/api"
import jnavigator from "@/_js/navigator"
import jbroadcast from "@/_js/broadcast"

import jtrading from "./trading"

const weexFunction = weex.requireModule("WeexFunction")

import I18N from "@/_i18n/i18n";
var T = I18N.t;
export default {

  props:{
    configKey: { //缓存键
      type: String,
      default:'',
    },
    isPair: { //true获取交易对并显示
      type: Boolean,
      default:true,
    },
    
    // 支持交易所:['Huobi', 'Binance', 'OkexV5', 'CoinTR'], 
    exchanges: { 
      type: Array,
      default:['Binance'],
    },
  },
  data() {
    return {
      T:T,
      Config:jconfig,
      
      api:undefined, //选中api
      pair:undefined, //选中交易对
      
      count:0, //查询交易对信息错误次数，5次后停止重复查询
    };
  },

  mounted() {
    this.initConfigData();
  },

  methods: {
    /************************************************* 通信*/
    //完全显示
    viewappear() {
    },

    //完全隐藏
    viewdisappear() {
    },

    /********************************************** 初始化*/
    initConfigData() {
      if (!jconfig.isLogin) {
        this.initApi();
        return;
      }
      
      weexFunction.getConfig(this.configKey, (str)=>{

        if (!str) {
          this.initApi();
          return;
        }
        
        var map = JSON.parse(str);
        japi.getApi(map.api.apiId, 'YES', (newApi)=>{
          if (newApi) {
            this.httpQueryContractPair(newApi, map.pair);
          } else {
            this.initApi();
          }
        });
      });
    },

    initApi() {

      japi.getApis('YES', 'USDT', this.exchanges, (apis)=>{
        var api = apis.length ? apis[0] : undefined;
        if (api) {
          this.httpQueryContractPair(api);
        } else {
          japi.getMockApi(this.exchanges[0], (mockApi)=>{
            mockApi.apiName = mockApi.exchangeName;
            this.httpQueryContractPair(mockApi);
          });
        }
      });
    },
    
    //更新余额
    upAvailable() {

      if (!this.api.apiId) {
        !jconfig.isLogin && this.initConfigData();
        return;
      }

      japi.getApi(this.api.apiId, 'YES', (newApi)=>{
          if (newApi) {
            this.change(newApi, this.pair);
          } else {
            this.initApi();
          }
        });
    },
    
    /********************************************** https*/
    //http查询默认交易对信息
    httpQueryContractPair(api, pair) {

      //不获取交易对
      if (!this.isPair) {
        this.change(api)
        return;
      }

      jmodal.showLoad();
      //获取交易对
      var param = {'exchangeId':api.exchangeId, 
                   'counterCoin':pair ? pair.counterCoin : 'BTC', 
                   'type':'contract_usdt'};
      jhttps.post('quoteV3/queryContractPair',param,true,(data)=>{

        if(data.status == 200){
          this.count == 0;
          var pair = data.data[0];

          if(!api.apiId) {
            jmodal.hideLoad();
            pair.leverage = '20';
            pair.last = '';
            pair.increase = '';
            this.change(api, pair);
            return;
          }
          
          jtrading.gtApiRsaStr(api, true, true, (newRsa)=>{
            this.httpQueryLeverage(newRsa, api, pair);
          });
        } 

        //查询失败循环3次重复查询
        else if (this.count < 3) {
          this.count++;
          setTimeout(() => {
            this.initConfigData();
          }, 5000);
        } 

        //循环超过3次，清除缓存查询默认交易对
        else if (this.count < 5) {
          this.count++;
          setTimeout(() => {
            weexFunction.setConfig(this.configKey, '');
            this.initConfigData();
          }, 5000);
        }
        
        //失败5次以上，直接报错
        else {
          jmodal.hideLoad();
          jmodal.toast(data.msg);
        }
      });
    },

    //http查询杠杠倍率
    httpQueryLeverage(rsa, api, pair) {

      //获取交易对
      var param = {'apiData':rsa, 
                   'baseCoin':pair.baseCoin, 
                   'counterCoin':pair.counterCoin};
      jhttps.post('manual/queryLeverage',param,true,(data)=>{

        if (data.status == 11505) { 
          jtrading.delectApiRsaStr(true);
          jtrading.gtApiRsaStr(this.api, true, true, (newRsa)=>{
            this.httpQueryLeverage(newRsa, api, pair);
          });
          return;
        }
        
        jmodal.hideLoad();
        if(data.status == 200){
          var datas = data.data.leverageList;
          try {
            pair.leverage = datas[0].leverage;
          } catch (error) {
            pair.leverage = '20';
          }
        } else {
          pair.leverage = '20';
        }
        this.change(api, pair);
      });
    },


    /********************************************** 其他*/
    //api、pair改变
    change(api, pair){
      this.api = api;
      this.pair = pair;

      var str = JSON.stringify({api, pair});
      weexFunction.setConfig(this.configKey, str);
      this.$emit('change', api, pair);    
    },

    /********************************************** 点击*/
    //api
    apiClick(){
      if(!jconfig.forceLogin()) return;
      
      var param =  {'apiId':this.api.apiId, 'exchange':this.exchanges};
      jnavigator.openDialog('upContract/CSelectApi', param);
      jbroadcast.subscribeOnce('CSelectApi', (api)=>{
        if(api.apiId == this.api.apiId) return;

        this.change(api, this.pair);
      });
    },

    //交易对
    parClick(){
      if(!jconfig.forceLogin()) return;

      var param = {'exchangeId':this.api.exchangeId,
                  'counterCoin':this.pair.counterCoin,
                  'baseCoin':this.pair.baseCoin};
      jnavigator.open('', 'upContract/CSelectPair', param);
      jbroadcast.subscribeOnce('CSelectPair', (pair)=>{
        if(pair.baseCoin == this.pair.baseCoin && pair.counterCoin == this.pair.counterCoin) return;
        weexFunction.debugLog(pair)
        jmodal.showLoad();
        jtrading.gtApiRsaStr(this.api, true, true, (newRsa)=>{
          this.httpQueryLeverage(newRsa, this.api, pair);
        });
      });
    },
  }
};

</script>

<style src="@/_css/style.css" ></style>

<style scoped>

/*******************************头部容器*/
.vt-pair {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  height: 120px;
}
.img-exchange {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}
.img-arrow-down {
  width:16px;
  height:12px;
  margin-left: 12px;
}
</style>